import SocketConfig from "@/socket/config";
import { updateUserNetty} from "@/api/user";

export default {
  data() {
    return {
      heartBeatInterval: null,
      userLoginInterval: null,
    };
  },
  watch: {
    heartBeatInterval(newValue, oldValue) {
      if (oldValue) {
        clearInterval(oldValue);
      }
    },
    userLoginInterval(newValue, oldValue) {
      if (oldValue) {
        clearInterval(oldValue);
      }
    },
  },
  created() {
    if (this.$store.getters.websocket == null) {
      this.createSocket();
    }
  },

  methods: {
    // 创建WebSocket
    createSocket() {
      const websocket = new WebSocket(SocketConfig.SOCKET_URL);
      websocket.onopen = this.openSocket(websocket);
      websocket.onclose = this.closeSocket;
      // 收到消息
      websocket.onmessage = this.handlerMessage;
    },

    // 已创建链接打开链接
    openSocket(socket) {
      this.$store.dispatch("websocket/setWebSocket", socket);
      // 开启心跳检查
      this.sendHeartBeat();
      // 定时登录
      this.sendUserLogin();
    },

    // 链接关闭
    closeSocket() {
      this.$store.dispatch("websocket/clearWebSocket");
    },

    // 收到消息通知
    handlerMessage(res) {
      try {
        const response = res.data;
        if (response) {
          const nettyResponse = JSON.parse(response)
          this.$store.dispatch(
            "websocket/setSocketMessage",
            nettyResponse
          );

          // 更新用户netty信息
          if(Number(nettyResponse.msgType) === Number(601)) {
            this.updateUserNetty(nettyResponse)
          }
        }
      } catch (e) {
        console.log(e);
      }
    },

    // socket 心跳链接查询
    async sendHeartBeat() {
      try {
        this.heartBeatInterval = setInterval(async () => {
          try {
            const message = {
              msgType: SocketConfig.msgType.heartBeat,
              clientId: this.$store.getters.info.id,
              dateTime: this.$moment().format("YYYY-MM-DD HH:mm:ss"),
            };
            this.$store.getters.websocket.send(JSON.stringify(message));
          } catch (e) {
            this.createSocket();
            console.error(`socket定时发送消息异常:${e}`);
          }
        }, 5000);
      } catch (e) {
        this.sendHeartBeat();
      }
    },

    // 定时发送登录信息
    async sendUserLogin() {
      this.userLoginInterval = setInterval(() => {
        const clientId = this.$store.getters.info.id;
        if (clientId) {
          const message = {
            msgType: SocketConfig.msgType.login,
            clientId: clientId,
            dateTime: this.$moment().format("YYYY-MM-DD HH:mm:ss"),
          };
          this.$store.getters.websocket.send(JSON.stringify(message));
        }
      }, 1000 * 30);
    },

    // 更新用户netty信息
    async updateUserNetty(info) {
      const form = {
        id: info.clientId,
        channelId: info.channelId,
        isOnline: 1
      }
      await updateUserNetty(form)
    }
  },
};
